package edu.cug.water.crawler.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.cug.water.crawler.common.constant.Constant;
import edu.cug.water.crawler.common.utils.PageUtils;
import edu.cug.water.crawler.job.dao.ScheduleJobTimeTableDao;
import edu.cug.water.crawler.job.entity.ScheduleJobEntity;
import edu.cug.water.crawler.job.entity.ScheduleJobLogEntity;
import edu.cug.water.crawler.job.entity.ScheduleJobTimeTable;
import edu.cug.water.crawler.job.service.ScheduleJobLogService;
import edu.cug.water.crawler.job.service.ScheduleJobService;
import edu.cug.water.crawler.job.service.ScheduleJobTimeTableService;
import edu.cug.water.crawler.job.utils.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("scheduleJobTimeTableService")
public class ScheduleJobTimeTableServiceImpl extends ServiceImpl<ScheduleJobTimeTableDao, ScheduleJobTimeTable> implements ScheduleJobTimeTableService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ScheduleJobService scheduleJobService;
    
    @Autowired
    private ScheduleJobLogService scheduleJobLogService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String beanName = (String)params.get("beanName");

        List<ScheduleJobEntity> list = scheduleJobService.list();

        ArrayList<ScheduleJobTimeTable> results = new ArrayList<>();


        for (ScheduleJobEntity o : list) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, o.getJobId());

            ScheduleJobTimeTable scheduleJobTimeTable = new ScheduleJobTimeTable();
            scheduleJobTimeTable.setScheduleJobEntity(o).setNextFireTime(cronTrigger.getNextFireTime());

            ScheduleJobLogEntity one = scheduleJobLogService.getOne(new QueryWrapper<ScheduleJobLogEntity>().eq("job_id", o.getJobId()).orderByDesc("create_time").last("limit 1"));
            scheduleJobTimeTable.setLastJobLog(one);
            results.add(scheduleJobTimeTable);
        }

        List<ScheduleJobTimeTable> collect = results.stream().
                sorted(Comparator.comparing(ScheduleJobTimeTable::getNextFireTime)).
                collect(Collectors.toList());

        int curPage = 1;
        int limit = 20;

        if(params.get(Constant.PAGE) != null){
            curPage = Integer.parseInt((String)params.get(Constant.PAGE));
        }
        if(params.get(Constant.LIMIT) != null){
            limit = Integer.parseInt((String)params.get(Constant.LIMIT));
        }
        return new PageUtils(collect, results.size(), limit, curPage);
    }


}
